package com.blankland.dataanalysis.controller;

import cn.hutool.core.codec.PunyCode;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blankland.dataanalysis.domain.Menu;
import com.blankland.dataanalysis.domain.RoleMenu;
import com.blankland.dataanalysis.domain.vo.RoleMenuVO;
import com.blankland.dataanalysis.exception.GuiguException;
import com.blankland.dataanalysis.result.Result;
import com.blankland.dataanalysis.service.MenuService;
import com.blankland.dataanalysis.service.RoleMenuService;
import com.blankland.dataanalysis.utls.MenuHelperUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javafx.scene.input.Mnemonic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.annotation.ElementType;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "菜单管理接口")
@RestController
@RequestMapping("/admin/system/sysMenu")
public class MenuController {

    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleMenuService roleMenuService;


    /**
     * 获取所有的菜单（树形结构显示）
     *      一级菜单
     *          二级菜单
     *              按钮
     *              按钮
     */
    @ApiOperation("获取所有别的菜单，树形结构")
    @GetMapping("/findNodes")
    public Result findNodes(){
        List<Menu> list = menuService.list();
        List<Menu> menuNode = MenuHelperUtils.buildTree(list);
        return Result.ok(menuNode);
    }


    /**
     * 添加菜单
     * @param menu
     * @return
     */
    @ApiOperation("添加菜单")
    @PostMapping("/save")
    public Result save(Menu menu){
        boolean flag = menuService.save(menu);
        if (true == flag){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }

    /**
     * 根据id查询菜单
     * @param id
     * @return
     */
    @ApiOperation("根据id查询菜单")
    @GetMapping("/findNode/{id}")
    public Result findNodeByid(@PathVariable Long id){
        Menu menu = menuService.getById(id);
        return Result.ok(menu);
    }

    /**
     * 修改菜单
     * @param menu
     * @return
     */
    @ApiOperation("修改菜单")
    @PutMapping("/update")
    public Result updateById(Menu menu){
        boolean flag = menuService.updateById(menu);
        if (true == flag){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }


    /**
     * 删除菜单
     * @param id
     * @return
     */
    @ApiOperation("删除菜单")
    @DeleteMapping("/remove/{id}")
    public Result remove(@PathVariable Long id){
        //1、查询当前删除菜单下面是否有子菜单
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Menu> list = menuService.list(wrapper);

        //2、判断list中是否有值
        if (list.size()>0){
            throw new GuiguException(201,"请先删除子菜单，再删除该菜单");
        }else {
            boolean flag = menuService.removeById(id);
            if (true == flag){
                return Result.ok();
            }else {
                return Result.fail();
            }
        }


    }


    /**
     * 更新菜单状态
     * @param id
     * @param status
     * @return
     */
    @ApiOperation(value = "更新Menu状态")
    @PutMapping("/updateMenuStatus/{id}/{status}")
    public Result updataUserStatus(@PathVariable Integer id, @PathVariable Integer status){
        Menu menu = menuService.getById(id);
        menu.setStatus(status);
        menuService.updateById(menu);
        return Result.ok();
    }

    @ApiOperation("根据角色id获取该角色对应的所有菜单")
    @GetMapping("/toAssign/{roleId}")
    public Result toAssing(@PathVariable Long roleId){

        //1、针对sys_menu表，查询所有status=1的菜单
        QueryWrapper<Menu> menuQueryWrapper = new QueryWrapper<>();
        menuQueryWrapper.eq("status",1);
        List<Menu> menuList = menuService.list(menuQueryWrapper);

        //2、针对sys_role_menu，根据roleId查询对应的所有menu
        QueryWrapper<RoleMenu> roleMenuQueryWrapper = new QueryWrapper<>();
        roleMenuQueryWrapper.eq("role_id", roleId);
        List<RoleMenu> list = roleMenuService.list(roleMenuQueryWrapper);

        //3、从第二步查询的列表中，获取menu的id
        List<Long> roleMenuIds = list.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());


        //4、数据处理：isSelect如果选中为true，否则为false
        // 使用分配菜单id 和 所有菜单对比，有相同的让isSelect值为true
        for (Menu menu : menuList) {
            if (roleMenuIds.contains(menu.getId())){
                menu.setSelect(true);
            }else {
                menu.setSelect(false);
            }
        }

        //5、将处理好的所有菜单集合转成树形结构，用于前端展示
        List<Menu> buildTree = MenuHelperUtils.buildTree(menuList);

        return Result.ok(buildTree);


    }



    /**
     * 给角色分配菜单
     * @param roleMenuVO
     * @return
     */
    @ApiOperation(value = "给角色分配菜单")
    @PutMapping("/doAssign")
    public Result doAssign(@RequestBody RoleMenuVO roleMenuVO){
        //1、针对sys_role_menu表，根据role_id删除对应的Menu_id
        QueryWrapper<RoleMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id",roleMenuVO.getRoleId());
        roleMenuService.remove(wrapper);

        //2、遍历菜单id列表，一个一个进行添加
        List<Long> menuIdList = roleMenuVO.getMenuIdList();
        for (Long menuId : menuIdList) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleMenuVO.getRoleId());
            roleMenu.setMenuId(menuId);
            roleMenuService.save(roleMenu);
        }

        return Result.ok();
    }






}
